<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />
	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import { ReceiveArticleHandlApi, ReceiveArticleHandleVO } from '@/api/oa/receivedManagement'
import { useMessage, useToast } from 'wot-design-uni'
import { formatDate, parseDateToTimestamp } from '@/utils/formatTime'
import { getFileName, parseArrayField, buildFileList } from '@/utils/fileUtils'


const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)  //页面详情id
const resubmit = ref(0)

// 指定审批人
const processDefineKey = ref<string>('oa_receive') // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)
// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	document: [],
	attachments: []
})
/** 处理类型变更 */
const handleTypeChange = async ({ value }: { value: any }) => {
	console.log('value', value);

	startUserSelectTasks.value = []
	startUserSelectAssignees.value = {}
	if (value === undefined || value === null) return
	try {
		// 根据不同类型获取不同的流程定义Key
		const processKeyMap: Record<number, string> = {
			0: 'oa_receive', // 普通收文
			1: 'oa_erjishouwen', // 二级企业收文
		}
		processDefineKey.value = processKeyMap[value] || ''
		const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
			undefined,
			processDefineKey.value
		)
		if (!processDefinitionDetail) {
			toast.error('流程模型未配置，请检查！')
			return
		}
		startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
		console.log('startUserSelectTasks.value', startUserSelectTasks.value);

		// 设置指定审批人
		if (startUserSelectTasks.value?.length > 0) {
			// 设置校验规则
			for (const userTask of startUserSelectTasks.value) {
				startUserSelectAssignees.value[userTask.id] = []
				startUserSelectAssigneesFormRules.value[userTask.id] = [
					{
						required: true,
						message: '请选择审批人',
						validator: (value: any) => {
							if (value && Array.isArray(value) && value.length > 0) {
								return Promise.resolve();
							} else {
								return Promise.reject('审批人不能为空');
							}
						},
						trigger: ['change']

					}
				]
			}
		}
	} catch (error) {
		toast.error('获取流程定义失败，请重试')
	}
}
//表单项字段配置
const formFields = ref<any[]>([

	{ type: 'input', prop: 'documentNumber', label: '来文编号', placeholder: '保存时自动生成', readonly: true },
	{
		type: 'select', prop: 'type', label: '类型', placeholder: '请选择类型',
		options: getIntDictOptions(DICT_TYPE.OA_IN_TYPE),
		valueKey: 'value',
		labelKey: 'label',
		clearable: true,
		filterable: true,
		showConfirm: false,
		multiple: false,
		onChange: handleTypeChange
	},
	{ type: 'input', prop: 'fromAgency', label: '来文机关', placeholder: '请输入来文机关' },
	{ type: 'input', prop: 'documentCode', label: '来文文号', placeholder: '请输入来文文号' },
	{
		type: 'select', prop: 'secretLevel', label: '紧急程度', placeholder: '请选择紧急程度',
		options: getIntDictOptions(DICT_TYPE.OA_SECRET_LEVEL), // 绑定计算属性
		valueKey: 'value', labelKey: 'label',
	},
	{ type: 'input', prop: 'subject', label: '事由', placeholder: '请输入事由' },
	{ type: 'datetime', prop: 'receptionTime', label: '收文时间', placeholder: '请输入时间', datetimeType: 'date' },
	{
		type: 'upload', prop: 'document', label: '正文', placeholder: '请输入正文',
		action: globalConfig.uploadUrl,
		limit: 1,
		accept: 'all',
		isMultipleArray: true,
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'mainTextUrl',    // 接口返回ID -> formData.serverIds
			fileName: 'mainTextName'     // 文件名 -> formData.fileName
		}
	},

	{
		type: 'upload', prop: 'attachments', label: '附件', placeholder: '请输入附件',
		action: globalConfig.uploadUrl,
		limit: 0,
		accept: 'all',
		isMultipleArray: true,
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'eids',    // 接口返回ID -> formData.serverIds
			fileName: 'ename'     // 文件名 -> formData.fileName
		}
	},

])
const formData = ref<ReceiveArticleHandleVO>({
	type: 0
} as any)

const formRules = reactive({
	type: [{ required: true, message: '请选择类型', trigger: 'change' }],
	fromAgency: [{ required: true, message: '来文机关不能为空', trigger: 'blur' }],
	documentCode: [{ required: true, message: '来文文号不能为空', trigger: 'blur' }],
	secretLevel: [{ required: true, message: '紧急程度不能为空', trigger: 'blur' }],
	subject: [{ required: true, message: '事由不能为空', trigger: 'blur' }],
	receptionTime: [{ required: true, message: '收文时间不能为空', trigger: 'blur' }],
})



onLoad(async (options) => {
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey.value
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
		console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
		console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
})


/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await ReceiveArticleHandlApi.getReceiveArticleHandle(Number(detailId.value))
		formData.value = data
		if (formData.value.receptionTime) {
			formData.value.receptionTime = parseDateToTimestamp(formData.value.receptionTime)
		}
		// 附件字段回显
		formData.value.eids = parseArrayField(data.eids);
		formData.value.ename = parseArrayField(data.ename);
		formData.value.mainTextUrl = parseArrayField(data.mainTextUrl);
		formData.value.mainTextName = parseArrayField(data.mainTextName);
		fileLists.value.document = buildFileList(formData.value.mainTextUrl, formData.value.mainTextName);
		fileLists.value.attachments = buildFileList(formData.value.eids, formData.value.ename);
	} catch (error) {
		console.log('加载数据失败')
	}
}

/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	try {
		if (type === 'update') {
			await ReceiveArticleHandlApi.updateReceiveArticleHandle(data)
			toast.success('编辑成功');
		} else {
			await ReceiveArticleHandlApi.createReceiveArticleHandle(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/incomingDocument/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}
/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/incomingDocument/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>